package com.example.xinlijiankangsys.service;

import com.example.xinlijiankangsys.mapper.QuestionnaireMapper;
import com.example.xinlijiankangsys.pojo.QuestionnaireRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class QuestionnaireService {
    private static final Logger log = LoggerFactory.getLogger(QuestionnaireService.class);

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    /**
     * 添加或更新问卷记录
     */
    public boolean saveQuestionnaireRecord(QuestionnaireRecord record) {
        try {
            int affectedRows = questionnaireMapper.insertOrUpdateQuestionnaireRecord(record);
            return affectedRows > 0;
        } catch (Exception e) {
            log.error("保存问卷记录失败 - questionnaireId: {}, userId: {}",
                    record.getQuestionnaireId(), record.getUserId(), e);
            return false;
        }
    }

    /**
     * 批量保存问卷记录
     */
    @Transactional
    public boolean batchSaveRecords(List<QuestionnaireRecord> records) {
        if (records == null || records.isEmpty()) {
            return true;
        }

        try {
            records.forEach(this::saveQuestionnaireRecord);
            return true;
        } catch (Exception e) {
            log.error("批量保存问卷记录失败", e);
            throw new RuntimeException("批量保存问卷记录失败", e);
        }
    }

    /**
     * 获取用户问卷记录
     */
    public QuestionnaireRecord getRecord(int questionnaireId, int userId) {
        try {
            return questionnaireMapper.selectByPrimaryKey(questionnaireId, userId);
        } catch (Exception e) {
            log.error("查询问卷记录失败 - questionnaireId: {}, userId: {}",
                    questionnaireId, userId, e);
            return null;
        }
    }

    /**
     * 获取用户所有问卷记录
     */
    public List<QuestionnaireRecord> getUserRecords(String userId) {
        try {
            return questionnaireMapper.selectByUserId(userId);
        } catch (Exception e) {
            log.error("查询用户问卷记录失败 - userId: {}", userId, e);
            return Collections.emptyList();
        }
    }

    /**
     * 获取问卷的所有用户记录
     */
    public List<QuestionnaireRecord> getQuestionnaireRecords(int questionnaireId) {
        try {
            return questionnaireMapper.selectByQuestionnaireId(questionnaireId);
        } catch (Exception e) {
            log.error("查询问卷用户记录失败 - questionnaireId: {}", questionnaireId, e);
            return Collections.emptyList();
        }
    }

    /**
     * 删除问卷记录
     */
    public boolean deleteRecord(int questionnaireId, String userId) {
        try {
            return questionnaireMapper.deleteByPrimaryKey(questionnaireId, userId) > 0;
        } catch (Exception e) {
            log.error("删除问卷记录失败 - questionnaireId: {}, userId: {}",
                    questionnaireId, userId, e);
            return false;
        }
    }

    /**
     * 获取用户问卷得分
     */
    public Integer getUserQuestionnaireScore(int questionnaireId, String userId) {
        try {
            return questionnaireMapper.getScoreByUserAndQuestionnaire(questionnaireId, userId);
        } catch (Exception e) {
            log.error("获取用户问卷得分失败 - questionnaireId: {}, userId: {}",
                    questionnaireId, userId, e);
            return null;
        }
    }

    /**
     * 获取问卷平均分
     */
    public Double getQuestionnaireAverageScore(int questionnaireId) {
        try {
            return questionnaireMapper.getAverageScoreByQuestionnaire(questionnaireId);
        } catch (Exception e) {
            log.error("获取问卷平均分失败 - questionnaireId: {}", questionnaireId, e);
            return null;
        }
    }

    /**
     * 检查用户是否已完成问卷
     */
    public boolean hasUserCompletedQuestionnaire(int questionnaireId, String userId) {
        try {
            return questionnaireMapper.existsByUserAndQuestionnaire(questionnaireId, userId) > 0;
        } catch (Exception e) {
            log.error("检查用户问卷完成状态失败 - questionnaireId: {}, userId: {}",
                    questionnaireId, userId, e);
            return false;
        }
    }

    /**
     * 获取用户完成的问卷数量
     */
    public int countUserCompletedQuestionnaires(String userId) {
        try {
            return questionnaireMapper.countByUserId(userId);
        } catch (Exception e) {
            log.error("统计用户问卷完成数量失败 - userId: {}", userId, e);
            return 0;
        }
    }
    /**
    * 检测用户是否需要预警
    */
    public boolean checkUserNeedWaring(String userId){
        return questionnaireMapper.needsWarning(userId,80);
    }
}